<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:replace="fragment/head"/>
    <!-- BEGIN Page level plugins -->
    <link href="resources/assets/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css"/>
    <link href="resources/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet"
          type="text/css"/>
    <link href="resources/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css" rel="stylesheet"
          type="text/css"/>
</head>

<body class="page-header-fixed page-sidebar-closed-hide-logo page-container-bg-solid page-content-white page-sidebar-closed">
<th:block th:with="
    ERPConstants = ${T(com.sh.caryr.erp.util.ERPConstants)} ,
    authTarget = ${ERPConstants.AUTH_TARGET_USER} ,
    layout = ${T(com.sh.caryr.erp.custmz.LayoutContainer).getLayout(authTarget, session.user)},
    createAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_CREATE},
    deleteAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_DELETE},
    updateAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_UPDATE}
">
    <th:block th:replace="fragment/header"/>
    <!-- BEGIN CONTAINER -->
    <div class="page-container">
        <!-- BEGIN SIDEBAR -->
        <th:block th:replace="fragment/sidebar"/>
        <!-- BEGIN CONTENT -->
        <div class="page-content-wrapper">
            <!-- BEGIN CONTENT BODY -->
            <div class="page-content">
                <!-- BEGIN PAGE BAR -->
                <div class="page-bar">
                    <ul class="page-breadcrumb">
                        <li><a href="index.html" class='msg_home'>主页</a> <i class="fa fa-circle"></i></li>
                        <li><span class='msg_title_trade'>Current Page</span></li>
                    </ul>
                </div>
                <!-- BEGIN PAGE TITLE-->
                <h1 class="page-title">
                    <span class="msg_title_trade"> PageTitle</span>
                    <small class="">订单批量导入</small>
                </h1>
                <!-- BEGIN main content -->
                <div class="row">
                    <!-- BEGIN ===========page level content============= -->
                    <div class="col-md-12">
                        <div class="alert alert-success">
                            <strong>导入流程</strong>
                            选择上传文件 -> 上传文件 -> 等待结果 -> 选择数据 ->
                            <span class="font-red-sunglo">上传订单 (同步数据到服务器)</span>
                        </div>
                        <!-- BEGIN Error Message -->
                        <div class="alert alert-danger hidden" id="form_error_msg">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                            <strong class="msg_err_title"></strong>
                            <span class="msg_err_subTitle"> </span>
                        </div>
                        <div class='row'>
                            <div class="col-md-12">
                                <!-- File upload form -->
                                <div class="portlet light ">
                                    <div class="portlet-body form">
                                        <form id='upload_trade_form' action="api/upload/trades" class="horizontal-form"
                                              enctype="multipart/form-data" method="post">
                                            <div class="form-body">
                                                <div class="row">
                                                    <div class="form-group col-md-4">
                                                        <label class="col-md-4" for="input_file_upload">上传文件</label>
                                                        <input class="col-md-8" name="uploadFile" type="file"
                                                               id="input_file_upload">
                                                    </div>
                                                    <div class="col-md-4">
                                                        <button type="button" class="btn blue" id="btn_upload_trade">
                                                            <i class="fa fa-cloud-upload"></i> 上传文件
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                                <!-- BEGIN: summary form -->
                                <div class="portlet light list_filter_form">
                                    <div class="portlet-title">
                                        <div class="caption">
                                            <i class="fa fa-list-alt font-red-sunglo"></i>
                                            <span class="caption-subject font-red-sunglo bold uppercase">预览选中清单</span>
                                            <span class="caption-helper"></span>
                                        </div>
                                        <div class="tools">
                                            <a href="" class="collapse" data-original-title="" title=""> </a>
                                            <a href="" class="remove" data-original-title="" title=""> </a>
                                        </div>
                                    </div>
                                    <div class="portlet-body form">
                                        <form action="#" id="trade_import_summary_form" class="horizontal-form">
                                            <div class="form-body"></div>
                                        </form>
                                    </div>
                                </div>
                                <!-- BEGIN data table-->
                                <div class="portlet box green datatable-portlet">
                                    <div class="portlet-title">
                                        <div class="caption">
                                            <i class="fa fa-list"></i><span class='msg_listTitle'>列表</span>
                                        </div>
                                        <div class="tools">
                                            <button class="btn sbold green" id="btn_save_import">
                                                <i class="fa fa-save"> 上传订单 </i>
                                            </button>
                                            <div class="btn sbold green">
                                                <a class="btn sbold green"
                                                   href="api/download/template/?filename=trade_order_orig.xlsx"
                                                   target="_blank"><i
                                                        class="fa fa-file-text-o"></i> 下载模版 </a>
                                            </div>
                                            <button id="btn_refresh_dt" class="btn sbold green">
                                                <i class="fa icon-refresh"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="portlet-body">
                                        <table class="table table-striped table-bordered table-hover dt-responsive"
                                               id="dt_trade" cellspacing="0" width="100%">
                                            <thead>
                                            <tr>
                                                <th width="2%">
                                                    <label
                                                            class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
                                                        <input type="checkbox" class="group-checkable"
                                                               data-set="#dt_trade .checkboxes"/>
                                                        <span></span>
                                                    </label></th>
                                                <th width='' class='msg_ent_fld_sys_trd_id'></th>
                                                <th width='' class='msg_ent_fld_receiver'></th>
                                                <th width='' class='msg_ent_fld_phone'></th>
                                                <th width='' class='msg_ent_fld_address'></th>
                                                <th width='' class='msg_ent_fld_expressName'></th>
                                                <th width='' class='msg_ent_fld_expressOrderId'></th>
                                                <th width='' class=''>买家备注</th>
                                                <th width='' class=''>系统备注</th>
                                                <th width='' class='msg_ent_fld_trd_status'></th>
                                            </tr>
                                            </thead>
                                        </table>
                                    </div>
                                </div>
                                <!-- END data table-->
                            </div>
                        </div>
                    </div>
                    <!-- END ===========page level content============= -->
                </div>
            </div>
        </div>
    </div>

    <th:block th:replace="fragment/rear"/>
    <!-- BEGIN Page level plugins -->
    <script src="resources/assets/global/plugins/datatables/datatables.min.js"></script>
    <script src="resources/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js"></script>
    <script src="resources/assets/jquery.form.js"></script>
    <script src="resources/assets/caryr/caryr.datatable.js" type="text/javascript"></script>
    <script th:inline="javascript">
        jQuery(document).ready(function () {
            /*[+
            caryr.lang = [[${session.lang}]];
            +]*/

            var tableId = '#dt_trade';
            /************ Upload form ****************/
            var uploadForm = $("#upload_trade_form");
            uploadForm.ajaxForm(function (data) {
                App.unblockUI();
                $("#input_file_upload").val("");
                dataTable.draw();
            });

            $("#btn_upload_trade").on("click", function () {
                if ($("#input_file_upload").val()) {
                    App.blockUI();
                    uploadForm.submit();
                } else {
                    var msgTxt = "请先选择需要导入的文件!";
                    swal({
                        title: msgTxt,
                        text: "",
                        type: ""
                    });
                }
            });

            $("#btn_save_import").on("click", function () {
                //check selected row
                var table = dataTable;
                var url = "api/upload/saveTrades";
                var selectData = table.rows('.selected').indexes();
                if (selectData.length == 0) {
                    swal($.i18n.prop("msg_com_noDataSelect"), "", "error");
                    return;
                }
                //collect selected Id
                var ids = new Array();
                selectData.each(function (e, i) {
                    ids.push(e);
                })
                requestUpdateEntities({
                    ids: ids,
                    url: url,
                    method: "GET",
                    success: function () {
                        table.draw();
                    },
                    error: function () {
                        table.draw();
                    }
                });
            });
            /***************** dataTable **************/
            var dataTable = caryr.dataTable.create({
                url: "api/upload/orders",
                defaultOrderBy: 1,
                tableId: tableId,
                lang: caryr.lang,
                pageLength: -1,
                disableView: true,
                columns: [
                    {data: 'id'},
                    {data: 'receiver'},
                    {data: 'phoneNum'},
                    {data: 'address'},
                    {
                        data: 'tradeOrderList',
                        render: function (tradeOrderList) {
                            if (tradeOrderList && tradeOrderList.length) {
                                return tradeOrderList[0].expressName;
                            }
                            return "";
                        }
                    },
                    {
                        data: 'tradeOrderList',
                        render: function (tradeOrderList) {
                            if (tradeOrderList && tradeOrderList.length) {
                                return tradeOrderList[0].expressOrderId;
                            }
                            return "";
                        }
                    },
                    {data: 'customRemark'},
                    {data: 'systemRemark'},
                    {
                        data: 'status',
                        render: orderStatusHtml
                    }

                ],
                checkEvent: function () {
                    refreshSummaryForm();
                },
                checkAllEvent: function () {
                    refreshSummaryForm();
                }
            });

            /***************** Functions **************/
            function orderStatusHtml(status) {
                var style = "label-default";
                if (status == null) {
                    return "";
                } else if (status == 10) {
                    style = "label-default";
                } else if (status <= 80) {
                    style = "label-danger";
                } else if (status == 100) {
                    style = "label-success";
                } else {
                    style = "label-warning";
                }
                var msgClass = "msg_trade_std_" + status;
                return "<span class='label label-sm " + style + " " + msgClass + "'></span>";
            }

            function requestUpdateEntities(option) {
                var url = option.url + '/' + caryr.ids2UrlParam(option.ids);
                var ids = option.ids;
                swal({
                    title: "确定要更新这些订单吗？",
                    confirmButtonText:$.i18n.prop("msg_com_formOK"),
                    cancelButtonText:$.i18n.prop("msg_com_formCancel"),
                    text: "",
                    type: "info",
                    showCancelButton: true,
                    closeOnConfirm: false,
                    showLoaderOnConfirm: true
                }, function () {
                    $.ajax({
                        type: option.method,
                        url: url,
                        traditional: true, //参数序列化的传统样式
                        data: {
                            ids: ids
                        },
                        success: function (data) {
                            var msgTxt = "订单更新成功";
                            swal({
                                title: msgTxt,
                                text: "",
                                type: "success"
                            }, function () {
                                if (option.success) {
                                    option.success();
                                }
                            });
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            var msgTxt = "";
                            if (XMLHttpRequest && XMLHttpRequest.responseJSON) {
                                msgTxt = $.i18n.prop("msg_err_" + XMLHttpRequest.responseJSON.code);
                            }
                            var reg = /^\[.*\]$/;
                            if (reg.test(msgTxt)) {
                                msgTxt = $.i18n.prop("msg_com_systemError");
                            }
                            swal({
                                title: msgTxt,
                                text: "",
                                type: "error"
                            }, function () {
                                if (option.error) {
                                    option.error();
                                }
                            });
                        }
                    });
                });
            };

            function refreshSummaryForm() {
                //---------- Clear summary form
                var formBody = $('#trade_import_summary_form').find('div.form-body');
                formBody.html('');
                //----------- Get selected data
                var table = dataTable;
                var selectData = table.rows('.selected').data();
                if (selectData.length == 0) {
                    return;
                }
                var template = '', totalAmount = 0;
                for (var i = 0; i < selectData.length; i++) {
                    var order = selectData[i];
                    var orders = order.tradeOrderList;
                    var receiver = order.receiver ? order.receiver : '';
                    var phoneNum = order.phoneNum ? order.phoneNum : '';
                    for (var j = 0; j < orders.length; j++) {
                        var receiverAndTel = j == 0 ? receiver + phoneNum : '';
                        var productSpecName = orders[j].name;
                        var amount = orders[j].productAmount;
                        var price = orders[j].salePrice;
                        template =
                            '<div class="row">' +
                            '<p class="col-md-offset-1 col-md-2">' + receiverAndTel + '</p>' +
                            '<p class="col-md-3">' + productSpecName + '</p>' +
                            '<p class="col-md-3">' + price + '</p>' +
                            '<p class="col-md-3">' + amount + '</p> ' +
                            '</div>';

                        formBody.append(template);
                        totalAmount += price && amount ? price * amount : 0;
                    }
                }

                var summary = '<div class="row">' +
                    '<p class="col-md-offset-1 col-md-2">总金额</p>' +
                    '<p class="col-md-3">' + totalAmount + '</p>' +
                    '</div>';
                formBody.append(summary);
            }
        });
    </script>
</th:block>
</body>

</html>